﻿using Shop.Model.DB;
using Shop.RemoteModel.LogisticsConfig.Model;
using Shop.Repository.LinqHelper;
using SqlSugar;
using WeDonekRpc.Client;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.IdGenerator;
using WeDonekRpc.Model;
using WeDonekRpc.SqlSugar;

namespace Shop.Repository.lmpl
{
    internal class LogisticsConfigRepository : ShopBaseRepository<DBLogisticsConfig, long>, ILogisticsConfigRepository
    {
        public LogisticsConfigRepository (ISqlClientFactory factory) : base(factory)
        {
        }
        public LogisticsConfigDto[] GetAreaConfig (long templateId, int[] areaId)
        {
            ISugarQueryable<LogisticsConfigDto>[] table = new ISugarQueryable<LogisticsConfigDto>[]
            {
                base.Queryable.Where(a => a.TemplateId == templateId && areaId.Contains(a.AreaId) && a.IsEnable).Select<LogisticsConfigDto>(),
                base.Queryable.Where(a => a.TemplateId == templateId && a.AreaId == 0 && a.IsEnable).Select<LogisticsConfigDto>()
            };
            return base.Gets<LogisticsConfigDto>(table);
        }
        public long Add (LogisticsConfigAdd add)
        {
            DBLogisticsConfig data = add.ConvertMap<LogisticsConfigAdd, DBLogisticsConfig>();
            data.Id = IdentityHelper.CreateId();
            base.Insert(data);
            return data.Id;
        }
        public void SetIsEnable (long id, bool enable)
        {
            if (!base.Update(a => a.IsEnable == enable, a => a.Id == id))
            {
                throw new ErrorException("shop.logistics.config.set.fail");
            }
        }
        public Result[] Gets<Result> (LQueryParam query) where Result : class, new()
        {
            return base.Gets<Result>(query.ToWhere());
        }
        public Result[] Query<Result> (LQueryParam query, IBasicPage paging, out int count) where Result : class
        {
            paging.InitOrderBy("Id", true);
            return base.Query<Result>(query.ToWhere(), paging, out count);
        }
    }
}
